// pages/virtual-try-on/index.js
Page({
  data: {
    selfieLocal: '',
    selfiePreview: '',
    selfieFileID: '',
    productLocalPath: '',
    productPreview: '',
    productFileID: '',
    selfieVisible: true,
    generating: false,
    results: [],
    // clothes options
    clothesOptions: ['Upper-body','Lower-body','Dress'],
    clothesIndex: 0,
    productVisible: false
  },

  onLoad(options) {
    // nothing for now
  },

  // 选择并上传单张自拍
  async onChooseSelfie() {
    try {
      const chooseRes = await wx.chooseImage({ count: 1, sourceType: ['camera','album'] })
      const tempPath = chooseRes.tempFilePaths[0]
      this.setData({ selfieLocal: tempPath, selfiePreview: tempPath })
      const cloudPath = `virtual_tryon/${wx.getStorageSync('openid') || 'guest'}/${Date.now()}_selfie.jpg`
      const uploadRes = await wx.cloud.uploadFile({ filePath: tempPath, cloudPath })
      this.setData({ selfieFileID: uploadRes.fileID })
    } catch (err) {
      console.error('上传自拍失败', err)
      wx.showToast({ title: '上传自拍失败', icon: 'none' })
    }
  },

  // 选择并上传单张商品图
  async onChooseProducts() {
    try {
      const chooseRes = await wx.chooseImage({ count: 1, sourceType: ['album','camera'] })
      const tempPath = chooseRes.tempFilePaths[0]
      this.setData({ productLocalPath: tempPath, productPreview: tempPath })
      const cloudPath = `virtual_tryon/${wx.getStorageSync('openid') || 'guest'}/${Date.now()}_product.jpg`
      const uploadRes = await wx.cloud.uploadFile({ filePath: tempPath, cloudPath })
      this.setData({ productFileID: uploadRes.fileID, productVisible: true })
    } catch (err) {
      console.error('上传商品图片失败', err)
      wx.showToast({ title: '上传商品图片失败', icon: 'none' })
    }
  },

  toggleShowProducts() {
    this.setData({ showAllProducts: !this.data.showAllProducts })
  },

  toggleProductVisible() {
    this.setData({ productVisible: !this.data.productVisible })
  },

  toggleSelfieVisible() {
    this.setData({ selfieVisible: !this.data.selfieVisible })
  },

  // 通用图片预览（支持传入 data-src）
  onPreviewImage(e) {
    const src = e.currentTarget.dataset && (e.currentTarget.dataset.src || e.currentTarget.dataset.url)
    if (!src) return
    wx.previewImage({ urls: [src] })
  },

  backToPrev() {
    wx.navigateBack()
  },

  // 发起生成
  async onGenerate() {
    const { selfieFileID, productFileID, clothesIndex, clothesOptions } = this.data;
    const clothesType = (clothesOptions && clothesOptions[clothesIndex]) || 'Upper-body';
    if (!selfieFileID || !productFileID) {
      wx.showToast({ title: '请先上传自拍和商品图片', icon: 'none' });
      return;
    }
    this.setData({ generating: true });
    wx.showLoading({ title: '生成中，请稍候...' });

    try {
      const callRes = await wx.cloud.callFunction({
        name: 'virtualTryOn',
        data: { selfieFileID, productFileID, clothesType }
      });
      
      const result = callRes.result;

      if (result && result.success) {
        // 1. 从后端获取 FileID
        const resultFileID = result.result_file_id;
        if (!resultFileID) throw new Error('后端未返回 file_id');
        
        // 2. 将 FileID 转换为临时 URL
        const tmp = await wx.cloud.getTempFileURL({ fileList: [resultFileID] });
        const downloadUrl = (tmp.fileList && tmp.fileList[0] && tmp.fileList[0].tempFileURL) || '';
        if (!downloadUrl) throw new Error('换取下载链接失败');
        // 3. 构造结果对象时，把 fileId 和 downloadUrl 都存进去
        const newResult = {
          fileId: resultFileID,
          downloadUrl: downloadUrl
        };
        this.setData({
          results: [newResult, ...this.data.results]
        });

      } else {
        throw new Error((result && result.error) || 'AI 处理失败');
      }
    } catch (err) {
      console.error('onGenerate 全流程出错:', err);
      wx.showToast({ title: '生成失败: ' + err.message, icon: 'none' });
    } finally {
      wx.hideLoading();
      this.setData({ generating: false });
    }
  },

  // 下载生成结果（保存到相册或预览）
  async onDownloadResult(e) {
    const url = e.currentTarget.dataset.url
    if (!url) {
      wx.showToast({ title: '无可下载链接', icon: 'none' })
      return
    }
    wx.showLoading({ title: '准备下载...' })
    try {
      const dl = await new Promise((resolve, reject) => {
        wx.downloadFile({ url, success: res => resolve(res), fail: err => reject(err) })
      })
      const tempPath = dl.tempFilePath
      // 尝试保存到相册（需要用户授权）
      wx.saveImageToPhotosAlbum({ filePath: tempPath, success() {
        wx.hideLoading()
        wx.showToast({ title: '已保存到相册' })
      }, fail(err) {
        wx.hideLoading()
        // 无法保存则预览图片
        wx.previewImage({ urls: [tempPath] })
      }})
    } catch (err) {
      wx.hideLoading()
      wx.showToast({ title: '下载失败', icon: 'none' })
      console.error('download result failed', err)
    }
  },

  onClothesTypeChange(e) {
    const idx = parseInt(e.detail.value, 10) || 0
    this.setData({ clothesIndex: idx })
  },
  async getAiSuggestion(e){
    const fileId = e.currentTarget.dataset.fileid;
    const index = e.currentTarget.dataset.index;
    if (fileId === undefined || index === undefined) {
      wx.showToast({ title: '获取图片信息失败', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '稍等，正在思考', mask: true });
  
    try {
      const callRes = await wx.cloud.callFunction({
        name: 'getSuggestion',
        data: {
          resultImageFileID: fileId 
        }
      });
      const result = callRes.result;
      if (result && result.success) {
        const suggestionText = result.suggestion;
        const key = `results[${index}].suggestionText`;
        this.setData({
          [key]: suggestionText
        });
      } else {
        // 如果后端处理失败，抛出错误
        throw new Error((result && result.error) || '获取建议失败');
      }
    } catch (err) {
      // 捕获整个流程中的任何错误
      wx.showToast({ title: '获取建议失败: ' + err.message, icon: 'none' });
      console.error('getAiSuggestion 出错:', err);
    } finally {
      wx.hideLoading();
    }
  }
})

